<?php

namespace Axe\Http\Controllers;

use Axe\Models\Menu;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;

class MenuController extends AuthController
{
    protected $viewGroup = 'menu';

    public function index()
    {
        $list = $this->getModel()->getAllTree();

        return $this->vendorView($this->viewGroup.'.index', [
            'list' => $list,
        ]);
    }

    /**
     * @return Menu
     */
    public function getModel(): Model
    {
        return app(Menu::class);
    }

    public function store(Request $request)
    {
        $this->validate($request, [
            'name'   => 'required',
            'type'   => 'required',
            'url'    => '',
            'icon'   => '',
            'sort'   => 'required',
            'is_use' => 'required',
        ]);

        $data = [
            'name'   => $request->input('name'),
            'type'   => $request->input('type'),
            'url'    => $request->input('url'),
            'icon'   => $request->input('icon'),
            'sort'   => $request->input('sort'),
            'is_use' => $request->input('is_use'),
        ];
        $model = $this->getModel();
        $model->fill($request->only($data))->save();

        return $this->vendorJson($model->exists, null, '创建成功');
    }

    public function destroy($id)
    {
        $model = $this->getModel()->findOrFail($id);
        if ($model->hasChild()) {
            return $this->vendorJson(false, null, '请先删除子菜单');
        }

        return parent::destroy($id); // TODO: Change the autogenerated stub
    }
}
